package com.jpsl.core.reflection.wrapper;

import com.jpsl.core.reflection.property.AccessException;
import com.jpsl.core.reflection.property.Accessible;
import com.jpsl.core.reflection.property.MetaClass;

import java.util.List;

/**
 * java 对象包装
 *
 * @author 懒王猫
 */
public class BeanWrapper implements ObjectWrapper {

    private final Object obj;

    private final MetaClass metaClass;

    public BeanWrapper(Object obj, MetaClass metaClass) {
        this.obj = obj;
        this.metaClass = metaClass;
    }

    @Override
    public List<String> getProperties() {
        return metaClass.getProperties();
    }

    @Override
    public boolean hasGetter(String property) {
        return metaClass.getGetter(property).isPresent();
    }

    @Override
    public boolean hasSetter(String property) {
        return metaClass.getSetter(property).isPresent();
    }

    @Override
    public Object getValue(String property) {
        return metaClass.getGetter(property).map(getter -> {
            try {
                return getter.getValue(obj);
            } catch (AccessException e) {
                return null;
            }
        }).orElse(null);
    }

    @Override
    public Class<?> getGetterType(String property) {
        return metaClass.getGetter(property).map(Accessible::getType).orElse(null);
    }

    @Override
    public void setValue(String property, Object value) {
        metaClass.getSetter(property).ifPresent(setter -> {
            try {
                setter.setValue(obj, value);
            } catch (AccessException e) {
                //
            }
        });
    }

    @Override
    public Class<?> getSetterType(String property) {
        return metaClass.getSetter(property).map(Accessible::getType).orElse(null);
    }
}
